<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="老人姓名" style="margin-right:50px;" prop="elderlyName">
        <el-input v-model="queryParams.elderlyName" placeholder="请输入老人姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="床位号" style="margin-right:50px;" prop="bedNo">
        <el-input v-model="queryParams.bedNo" placeholder="请输入床位号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="background-color: #266FE8; color: white;" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="display: flex; justify-content: flex-end;" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" style="width: 150px; background-color: #266FE8; color: white;" plain icon="Plus"
          @click="handleAdd" v-hasPermi="['le:recharge:add']">新增</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="rechargeList" @selection-change="handleSelectionChange">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="充值单号" align="center" prop="rechargeNo" />
      <el-table-column label="老人姓名" align="center" prop="elderlySzh.name" />
      <el-table-column label="床位号" align="center" prop="bedNo" />
      <el-table-column label="充值金额" align="center" prop="rechargeAmount" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod" />
      <el-table-column label="充值凭证图片" align="center" prop="rechargeVoucher" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.rechargeVoucher" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作人" align="center" prop="sysUser.nickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改预存款充值对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="rechargeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="充值老人" prop="elderlyId">
          <el-select v-model="form.elderlyId" placeholder="请选择要充值的老人" @visible-change="handleElderlySelectVisible">
            <!-- <el-input v-model="elderlySearchKey" placeholder="搜索老人姓名..." clearable size="small"
              class="elderly-search-input" @input="handleElderlySearch" @keyup.enter="handleElderlySearch" /> -->
            <el-input v-model="elderlySearchKey" placeholder="搜索老人姓名..." clearable size="small"
              class="elderly-search-input" @input="handleElderlySearch" @keyup.enter="handleElderlySearch" />
            <el-option-group label="老人列表">
            <el-option v-for="dict in elderlyList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
            <!-- 下拉框分页按钮 -->
            <div class="select-pagination" v-if="elderlyTotal > 0">
              <el-button style="width: 45px; height: 30px;" icon="el-icon-arrow-left"
                @click="changeElderlyPage(currentElderlyPage - 1)" :disabled="currentElderlyPage === 1">上一页</el-button>
              <span class="page-info">
                {{ currentElderlyPage }} / {{ totalElderlyPages }}
              </span>
              <el-button style="width: 45px; height: 30px;" icon="el-icon-arrow-right"
                @click="changeElderlyPage(currentElderlyPage + 1)"
                :disabled="currentElderlyPage >= totalElderlyPages">下一页</el-button>
            </div>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" prop="rechargeAmount">
          <el-input v-model="form.rechargeAmount" type="number" placeholder="请输入充值金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="充值凭证图片" prop="rechargeVoucher">
          <image-upload v-model="form.rechargeVoucher" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Recharge">
import { listRecharge, getRecharge, delRecharge, addRecharge, updateRecharge } from "@/api/le/recharge"
import { listBalance, getBalance, delBalance, addBalance, updateBalance, updateBalancePre } from "@/api/le/balance"
import { listElderly } from "@/api/le/elderly"
import { useUserStore } from '@/store/modules/user'

// 使用
const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const { political_status } = proxy.useDict('political_status')

const rechargeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const elderlySearchKey = ref('')

// 老人下拉框分页相关
const elderlyTotal = ref(0)
const currentElderlyPage = ref(1)
const elderlyPageSize = ref(10) // 下拉框每页显示10条
const totalElderlyPages = ref(0)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elderlyId: null,
    elderlyName: null,
    bedNo: null
  },
  rules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

/** 老人姓名模糊搜索 */
const handleElderlySearch = () => {
  // 重置为第一页，携带搜索关键词请求后端
  currentElderlyPage.value = 1
  loadElderlyList(1)
}



/** 加载老人列表（带分页） */
const loadElderlyList = (page = 1) => {
  // 传递搜索关键词到后端（假设接口支持elderlyName参数模糊查询）
  listElderly({
    pageNum: page,
    pageSize: elderlyPageSize.value,
    name: elderlySearchKey.value  // 新增：搜索关键词
  }).then(response => {
    elderlyList.value = response.rows
    elderlyTotal.value = response.total
    totalElderlyPages.value = Math.ceil(elderlyTotal.value / elderlyPageSize.value)
  })
}

/** 老人下拉框显示/隐藏时触发 */
const handleElderlySelectVisible = (visible) => {
  if (visible) {
    currentElderlyPage.value = 1 // 重置为第一页
    loadElderlyList(1)
  }
}

/** 切换老人下拉框页码 */
const changeElderlyPage = (page) => {
  if (page < 1 || page > totalElderlyPages.value) return
  currentElderlyPage.value = page
  loadElderlyList(page)
}
const { queryParams, form, rules } = toRefs(data)

/** 查询预存款充值列表 */
function getList() {

  loading.value = true
  // console.log(queryParams.value);
  listRecharge(queryParams.value).then(response => {
    console.log(response);
    rechargeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    rechargeNo: null,
    elderlyId: null,
    rechargeAmount: null,
    paymentMethod: null,
    rechargeVoucher: null,
    remark: null,
    operator: null,
    createTime: null,
    updateTime: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null
  }
  elderlySearchKey.value = null
  proxy.resetForm("rechargeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加预存款充值"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRecharge(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改预存款充值"
  })
}

/** 提交按钮 */
function submitForm() {
  form.value.operator = userStore.id
  proxy.$refs["rechargeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecharge(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecharge(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })

        listBalance({ elderlyId: form.value.elderlyId }).then(response => {
          console.log(response);
          let balance_id;
          if (response.total > 0) {
            balance_id = response.rows[0].id
          }
          const balance = {
            id: balance_id,
            elderlyId: form.value.elderlyId,
            prepaymentBalance: form.value.rechargeAmount,
            operator: userStore.id,
            updateTime: form.value.createTime
          }

          updateBalancePre(balance).then(response => {
            console.log("预存款修改");
            proxy.$modal.msgSuccess("修改成功")
          })
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除预存款充值编号为"' + _ids + '"的数据项？').then(function () {
    return delRecharge(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('le/recharge/export', {
    ...queryParams.value
  }, `recharge_${new Date().getTime()}.xlsx`)
}

const elderlyList = ref([])
const getElderly = ref()
// function getElderlyList() {
//   loading.value = true
//   listElderly(getElderly.value).then(response => {
//     // console.log(response);
//     elderlyList.value = response.rows
//     total.value = response.total
//     loading.value = false
//   })
// }

getList()
</script>
<style scoped>
/* 核心：统一搜索输入框与选项的高度和样式 */
.elderly-search-input {
  /* Element UI的el-option默认高度为34px（包含内边距） */
  height: 34px !important;
  margin: 0 10px !important;
  /* 与选项左右边距一致 */
  width: calc(100% - 20px) !important;
  /* 减去左右边距 */
}

/* 去除输入框默认边框（可选，使其融入列表） */
::v-deep .elderly-search-input .el-input__inner {
  border-radius: 0;
  /* 与选项边框弧度一致 */
  border: 1px solid transparent;
  /* 初始透明边框 */
}

/* 鼠标悬停时显示边框（与选项hover效果呼应） */
::v-deep .elderly-search-input .el-input__inner:hover {
  border-color: #dcdfe6;
  /* 与选项hover边框色一致 */
}

/* 下拉框分页样式保持不变 */
.select-pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 8px 10px;
  border-top: 1px solid #eee;
  margin-top: 5px;
}
</style>
